from fastapi import FastAPI, Request
import json, uvicorn
from model import GLMModel, OpenAIModel
from translator import PDFTranslator

app = FastAPI()


@app.post("/pdf/translate")
async def translate(request: Request):
    json_post_raw = await request.json()
    json_post = json.dumps(json_post_raw)
    json_post_list = json.loads(json_post)
    model_name = json_post_list.get('model_name')
    api_key = json_post_list.get('api_key')
    pdf_file_path = json_post_list.get('pdf_file_path')
    file_format = json_post_list.get('file_format')
    output_file_path = json_post_list.get('output_file_path')
    target_language = json_post_list.get('target_language')
    model = OpenAIModel(model=model_name, api_key=api_key)
    translator = PDFTranslator(model)
    translate_output_file_path = translator.translate_pdf(pdf_file_path, file_format,
                                                          output_file_path=output_file_path,
                                                          target_language=target_language)
    response = {
        "result": translate_output_file_path,
        "code": 200,
        "message": "翻译结束"
    }
    return response

if __name__ == '__main__':
    uvicorn.run(app, host='127.0.0.1', port=8081, workers=1)